#!/bin/bash
script_base_folder=$(dirname "$0")
source "${script_base_folder}/onedrive.cfg"
source "${script_base_folder}/onedrive-base"
export json_parser="${script_base_folder}/json-parser"

echo "Please open the following URL in your browser and follow the steps until you see a blank page:"
echo -e "\033[04mhttps://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id=${api_client_id}&redirect_uri=${api_reply_url}\033[0m\n"
echo "When ready, please enter the value of the code parameter (from the URL you have been redirected) and press return"
read code
if [[ -n $(echo -n $code |grep -o 'code=.*') ]]; then
    code=$(echo -n $code |grep -o 'code=.*' |cut -d'=' -f2 |cut -d'&' -f1)
fi
api_json_result=$(curl -s -d "client_id=${api_client_id}&client_secret=${api_client_secret}&code=${code}&grant_type=authorization_code&redirect_uri=${api_reply_url}&resource=https://api.office.com/discovery/" -X POST "${api_auth_url}")

refresh_token=$(echo "${api_json_result}" | "${json_parser}" | grep -E "^refresh_token=" | cut -d= -f2-)
if [ "${refresh_token}" != "" ]; then
    filesystem_save_refresh_token "${refresh_token}"
    echo -e "\n\033[04mIt seems like we have a refresh token, so we are ready to go.\033[0m"
else
    echo -e "\n\033[04mSomething went wrong, here is the API response:\033[0m"
    echo "${api_json_result}"
fi
